
/************* 长连接工具类 *************/
export default class WebSocket {
    private options: any = {
        url: '',
        header: {
            'content-type': 'application/json'
        },
        protocols: ['wss://'],
        name: '1', // 任务名称
    }
    // 消息任务
    private StockTask: any = {};
    constructor(options?: any) {
        this.options = options;
    }
    // 返回所有stock任务
    public getStockTaskAll(): any {
        return this.StockTask;
    }
    // 返回指定stock任务
    public getStockTask(name: string): any {
        return this.StockTask[name];
    }
    /**
     * 创建stock任务
     * @returns 
     */
    public createTask(): Promise<any> {
        const teskName = this.options.name;
        const options = { ...this.options };
        delete options.name;
        return new Promise((resolve, reject) => {
            options.success = (res: any) => {
                resolve(res)
            }
            options.fail = (error: any) => {
                reject(error)
            }
            const stockTask: UniNamespace.SocketTask = uni.connectSocket(options)
            this.StockTask[teskName] = stockTask
        })
    }

    /**
     * 取消任务
     * @param name 任务名称
     * @param options 取消任务参数
     */
    public cleanTask(name: string, options: any = {}): Promise<any> {
        return new Promise((resolve: any, reject: any) => {
            if (this.StockTask[name]) {
                options.success = (res: any) => {
                    resolve(res)
                }
                options.fail = (error: any) => {
                    reject(error)
                }
                this.StockTask[name].close(options)
                delete this.StockTask[name];
            } else {
                reject(name + '任务不存在')
            }
        })
    }
}